<template>
  <view class="container">
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
    
    <view v-else class="pay-page">
      <!-- 订单信息 -->
      <view class="order-info">
        <text class="title">订单信息</text>
        <view class="info-item">
          <text class="label">订单号：</text>
          <text class="value">{{ orderId }}</text>
        </view>
        <view class="info-item">
          <text class="label">订单总额：</text>
          <text class="value amount">{{ formatPrice(totalAmount) }}</text>
        </view>
      </view>
      
      <!-- 支付方式 -->
      <view class="payment-section">
        <text class="title">支付方式</text>
        
        <!-- 积分余额 -->
        <view class="balance-info">
          <text class="balance-label">可用积分：</text>
          <text class="balance-value">{{ formatPoint(accountInfo.pointBalance) }}</text>
        </view>
        
        <!-- 支付方式选择 -->
        <view class="payment-methods">
          <view 
            class="payment-item" 
            :class="{ 'selected': paymentType === 'point' }"
            @click="selectPaymentType('point')"
          >
            <text class="method-name">积分支付</text>
            <text class="method-desc">可用{{ formatPoint(accountInfo.pointBalance) }}积分</text>
          </view>
          
          <view 
            class="payment-item" 
            :class="{ 'selected': paymentType === 'mixed' }"
            @click="selectPaymentType('mixed')"
          >
            <text class="method-name">混合支付</text>
            <text class="method-desc">积分+支付宝</text>
          </view>
        </view>
        
        <!-- 支付金额输入 -->
        <view v-if="paymentType === 'mixed'" class="amount-input">
          <text class="input-label">积分支付：</text>
          <input 
            class="amount-field" 
            type="digit" 
            v-model="pointAmountInput"
            :placeholder="'最多' + formatPoint(accountInfo.pointBalance)"
            @input="onPointAmountChange"
          />
          <text class="unit">分</text>
        </view>
        
        <!-- 支付金额显示 -->
        <view class="payment-summary">
          <view class="summary-item">
            <text class="summary-label">积分支付：</text>
            <text class="summary-value">{{ formatPrice(pointAmount) }}</text>
          </view>
          <view class="summary-item">
            <text class="summary-label">支付宝支付：</text>
            <text class="summary-value">{{ formatPrice(payAmount) }}</text>
          </view>
          <view class="summary-item total">
            <text class="summary-label">合计：</text>
            <text class="summary-value">{{ formatPrice(totalAmount) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 支付按钮 -->
      <view class="pay-button">
        <button 
          class="pay-btn" 
          :disabled="!canPay"
          @click="handlePay"
        >
          {{ payBtnText }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { payOrder } from '@/api/order.js'
import { getCurrentAccount } from '@/api/user.js'

export default {
  data() {
    return {
      orderId: null,
      totalAmount: 0,
      pointAmountInput: '', // 积分支付输入值
      paymentType: 'point', // 支付方式：point-积分支付，mixed-混合支付
      accountInfo: {}, // 账户信息
      loading: true
    }
  },
  computed: {
    // 积分支付金额（分）
    pointAmount() {
      if (this.paymentType === 'point') {
        return Math.min(this.totalAmount, this.accountInfo.pointBalance * 100)
      } else {
        return Math.min(parseInt(this.pointAmountInput) || 0, this.accountInfo.pointBalance * 100, this.totalAmount)
      }
    },
    
    // 支付宝支付金额（分）
    payAmount() {
      return Math.max(0, this.totalAmount - this.pointAmount)
    },
    
    // 是否可以支付
    canPay() {
      return this.pointAmount + this.payAmount === this.totalAmount
    },
    
    // 支付按钮文字
    payBtnText() {
      if (this.paymentType === 'point') {
        if (this.pointAmount < this.totalAmount) {
          return '积分不足，请选择混合支付'
        }
        return '积分支付'
      } else {
        if (this.payAmount > 0) {
          return '积分+支付宝支付'
        }
        return '积分支付'
      }
    }
  },
  onLoad(options) {
    this.orderId = options.orderId
    this.totalAmount = parseInt(options.amount) || 0
    
    if (this.orderId) {
      this.loadAccountInfo()
    } else {
      this.loading = false
      uni.showToast({
        title: '订单信息错误',
        icon: 'none'
      })
    }
  },
  methods: {
    // 加载账户信息
    async loadAccountInfo() {
      try {
        const res = await getCurrentAccount()
        this.accountInfo = res.data
        
        // 根据积分余额自动选择支付方式
        if (this.accountInfo.pointBalance * 100 >= this.totalAmount) {
          this.paymentType = 'point'
        } else {
          this.paymentType = 'mixed'
          this.pointAmountInput = (this.accountInfo.pointBalance * 100).toString()
        }
        
      } catch (error) {
        console.error('加载账户信息失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 选择支付方式
    selectPaymentType(type) {
      this.paymentType = type
      
      if (type === 'point') {
        // 积分支付，清空输入
        this.pointAmountInput = ''
      } else if (type === 'mixed') {
        // 混合支付，默认使用全部积分
        this.pointAmountInput = (this.accountInfo.pointBalance * 100).toString()
      }
    },
    
    // 积分金额输入变化
    onPointAmountChange(e) {
      let value = parseInt(e.detail.value) || 0
      
      // 限制输入范围
      value = Math.min(value, this.accountInfo.pointBalance * 100)
      value = Math.min(value, this.totalAmount)
      
      this.pointAmountInput = value.toString()
    },
    
    // 支付
    async handlePay() {
      if (!this.canPay) {
        uni.showToast({
          title: '支付金额不正确',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '支付中...'
        })
        
        await payOrder({
          orderId: this.orderId,
          payAmount: this.payAmount,
          payPointAmount: this.pointAmount
        })
        
        uni.hideLoading()
        
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        })
        
        // 延迟跳转到订单列表
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index/index'
          })
        }, 1500)
        
      } catch (error) {
        uni.hideLoading()
        console.error('支付失败:', error)
        uni.showToast({
          title: '支付失败',
          icon: 'none'
        })
      }
    },
    
    // 格式化价格
    formatPrice(price) {
      return (price / 100).toFixed(2) + '元'
    },
    
    // 格式化积分
    formatPoint(point) {
      return (point || 0).toFixed(2) + '分'
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 30rpx;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  color: #999;
  font-size: 28rpx;
}

.pay-page {
  max-width: 600rpx;
  margin: 0 auto;
}

.order-info, .payment-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 28rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  color: #333;
}

.amount {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.balance-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 30rpx;
}

.balance-label {
  font-size: 28rpx;
  color: #666;
}

.balance-value {
  font-size: 28rpx;
  color: #667eea;
  font-weight: bold;
}

.payment-methods {
  margin-bottom: 30rpx;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  transition: all 0.3s;
}

.payment-item:last-child {
  margin-bottom: 0;
}

.payment-item.selected {
  border-color: #667eea;
  background: #f8f9ff;
}

.method-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.method-desc {
  font-size: 24rpx;
  color: #999;
}

.amount-input {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  margin-bottom: 30rpx;
}

.input-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
}

.amount-field {
  flex: 1;
  height: 60rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  text-align: center;
}

.unit {
  font-size: 24rpx;
  color: #999;
  margin-left: 20rpx;
}

.payment-summary {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 30rpx;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-item.total {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
  font-weight: bold;
}

.summary-label {
  font-size: 28rpx;
  color: #666;
}

.summary-value {
  font-size: 28rpx;
  color: #333;
}

.summary-item.total .summary-label,
.summary-item.total .summary-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.pay-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.pay-btn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 12rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pay-btn::after {
  border: none;
}

.pay-btn[disabled] {
  background: #ccc;
  color: #999;
  opacity: 0.6;
}
</style>
